package swu.cx.defineviewgroup

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.ViewGroup

class childSolid:ViewGroup {
    private val space = 30
    constructor(context: Context, attr: AttributeSet):super(context,attr){}

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        var resultWidth = 0
        var resultHeight = 0

        //测量每个子控件
        measureChildren(widthMeasureSpec,heightMeasureSpec)
        //获取子控件的尺寸
        val childSize = getChildAt(0).measuredWidth
        resultWidth = if (childCount==1) childSize+2*space else childSize*2+3*space
        //计算有多少行控件
        val row = childCount/2+childCount%2
        resultHeight = (row+1)*space+row*childSize
        setMeasuredDimension(resultWidth,resultHeight)
    }
    override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {
            var left = space
            var top = space
            for (i in 0 until childCount){
                val child = getChildAt(i)
                child.layout(left,top,left+child.measuredWidth,top+child.measuredHeight)
                left = if (i%2==0) 2*space+child.measuredWidth else space
                if (i%2!=0){
                    top+=child.measuredHeight+space
                }
            }
    }
}